package com.im.common.exception;

import cn.dev33.satoken.exception.NotLoginException;
import com.im.common.enums.ResultEnum;
import com.im.common.result.JsonResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

/**
 * 全局异常处理器
 *
 * @author yunZhouJiaDi
 */
@Slf4j
@RestControllerAdvice
public class GlobalExceptionHandler {

    @ExceptionHandler(BusinessException.class)
    public JsonResult businessException(BusinessException e) {
        if (e.getCode() == null) {
            return JsonResult.failed(e.getMessage());
        }
        return JsonResult.error(e.getCode(), e.getMessage());
    }

    @ExceptionHandler(value = MethodArgumentNotValidException.class)
    public JsonResult handleValidException(MethodArgumentNotValidException e) {
        BindingResult bindingResult = e.getBindingResult();
        String message = null;
        if (bindingResult.hasErrors()) {
            FieldError fieldError = bindingResult.getFieldError();
            if (fieldError != null) {
                message = fieldError.getDefaultMessage();
            }
        }
        return JsonResult.error(ResultEnum.FAILED.getCode(), message);
    }

    @ExceptionHandler(value = NotLoginException.class)
    public JsonResult handleNotLoginException(NotLoginException e) {
        return JsonResult.error(ResultEnum.UNAUTHORIZED.getCode(), ResultEnum.UNAUTHORIZED.getMessage());
    }

}
